import util from './util'
const app = getApp();

/**
 * [fetch description]
 * @param  {[type]}  url      [description]
 * @param  {[type]}  method   ['GET' | 'POST' | 'UPLOAD']
 * @param  {[type]}  params   [description]
 * @param  {Boolean} hasToken [description]
 * @return {[type]}           [description]
 */
function fetch(url, method, params, hasToken = true) {

  // 转成 大写
  method = method.toLocaleUpperCase()

  // url
  if (params.header) {
    url = util.fetchOption(url, params.header)
  }

  // header
  let header = {
    "Content-Type": method == 'UPLOAD' ? "multipart/form-data" : "application/json"
  }

  if (hasToken) {
    header = Object.assign({}, header, {
      "api-token-sign": wx.getStorageSync('token')
    })
  }

  return new Promise((resolve, reject) => {
    if (method == 'UPLOAD') {
      wx.uploadFile({
        url: url,
        filePath: params.filepath,
        name: params.name,
        formData: params.body,
        header: header,
        success: res => {
          // 有响应
          apiMiddleWare.call(this, res, 'UPLOAD').then(json => {
            resolve(json)
          })
        },
        fail: res => {
          res.result = false
          apiMiddleWare.call(this, res, 'UPLOAD').then(json => {
            resolve(json)
          })
        }
      });
    } else {
      wx.request({
        url: url,
        method: method,
        data: params.body,
        header: header,
        success: res => {
          apiMiddleWare.call(this, res, method).then(json => {
            resolve(json)
          })
        },
        fail: res => {
          res.result = false
          apiMiddleWare.call(this, res, method).then(json => {
            resolve(json)
          })
        }
      });
    }
  })

}


function apiMiddleWare(res, method) {
  // console.log(res)
  // console.log(method)
  return new Promise((resolve, reject) => {
    let json = {}
    json = {
      result: false,
      data: res.data && res.data.Data ? res.data.Data : null,
      msg: res.data && res.data.Msg ? res.data.Msg : '数据获取失败'
    }
    //request success
    // 首先验证网络
    if (!res.result) {
      // 其次验证登录状态
      if (res.data && res.data.Code == '000002') {
        // 清除 所有 缓存数据
        wx.clearStorage()
        // app.clearAllPageState()
        wx.showToast({
          title: res.data.Msg || '登录已经失效',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        // 跳转至登录页面
        setTimeout(() => {
          wx.reLaunch({
            url: '/page/root/login/login',
          })
        }, 1500)
      } else {
        // 若登录成功
        if (res.statusCode == 200) {
          if (method && method == 'UPLOAD') {
            res.data = JSON.parse(res.data)
          }
          //数据获取成功或失败
          if (res.data.IsSuccess) {
            json = {
              result: true,
              // ?res.data.Data : []
              data: res.data.Data,
              msg: res.data.Msg
            }
          } else {
            if (method != 'GET') {
              wx.showToast({
                title: json.msg,
                icon: 'none',
                duration:2000,
                mask:true
              })
            }
          }
        } else {
          wx.showToast({
            title: '服务器错误,请稍后重试',
            icon: 'none',
            duration: 2000,
            mask: true
          })
        }
      }
    } else {
      //request fail，如果没有网络需要什么提示？
      wx.showToast({
        title: res.errMsg || '请求失败',
        icon: 'none',
        duration: 2000,
        mask: true
      })
    }
    // console.log(json)
    resolve(json)
  })
}



export default fetch